<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

interface Props {
  visible: boolean;
  record?: any;
}

interface Emits {
  (e: 'update:visible',value: boolean): void;
  (e: 'success',items: any[]): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const selectedCategory = ref('emergency');
const selectedItems = ref<string[]>([]);
const searchQuery = ref('');
const surgeryDate = ref(null);
const surgeryTime = ref(null);
const surgeon = ref('');
const anesthesiologist = ref('');
const surgeryNotes = ref('');

// 手术项目数据
const surgeryItems = ref([
  // 急诊手术
  {
    id: 'S001',
    category: 'emergency',
    name: '剖腹探查术',
    price: 2000,
    description: '腹部外伤或急腹症探查',
    duration: '2-3小时',
  },
  {
    id: 'S002',
    category: 'emergency',
    name: '气管切开术',
    price: 1500,
    description: '紧急气道建立',
    duration: '30分钟',
  },
  {
    id: 'S003',
    category: 'emergency',
    name: '止血手术',
    price: 1200,
    description: '外伤止血处理',
    duration: '1小时',
  },

  // 择期手术
  {
    id: 'S004',
    category: 'elective',
    name: '绝育手术',
    price: 800,
    description: '公猫/公狗绝育',
    duration: '1小时',
  },
  {
    id: 'S005',
    category: 'elective',
    name: '剖腹产',
    price: 1800,
    description: '难产剖腹产手术',
    duration: '2小时',
  },
  {
    id: 'S006',
    category: 'elective',
    name: '肿瘤切除术',
    price: 2500,
    description: '良性肿瘤切除',
    duration: '3-4小时',
  },

  // 小手术
  {
    id: 'S007',
    category: 'minor',
    name: '伤口缝合',
    price: 300,
    description: '外伤伤口缝合',
    duration: '30分钟',
  },
  {
    id: 'S008',
    category: 'minor',
    name: '脓肿切开引流',
    price: 400,
    description: '脓肿切开引流术',
    duration: '45分钟',
  },
  {
    id: 'S009',
    category: 'minor',
    name: '异物取出',
    price: 500,
    description: '消化道异物取出',
    duration: '1小时',
  },

  // 大手术
  {
    id: 'S010',
    category: 'major',
    name: '骨科手术',
    price: 3000,
    description: '骨折内固定术',
    duration: '4-5小时',
  },
  {
    id: 'S011',
    category: 'major',
    name: '心脏手术',
    price: 5000,
    description: '心脏瓣膜修复',
    duration: '6-8小时',
  },
  {
    id: 'S012',
    category: 'major',
    name: '神经手术',
    price: 4000,
    description: '神经系统手术',
    duration: '5-6小时',
  },
]);

// 表格列定义
const selectedColumns = [
  {
    title: '手术名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    width: 100,
  },
  {
    title: '预计时长',
    dataIndex: 'duration',
    key: 'duration',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
  },
];

// 计算属性
const filteredItems = computed(() => {
  let result = surgeryItems.value.filter(
    (item) => item.category === selectedCategory.value,
  );

  if (searchQuery.value) {
    const search = searchQuery.value.toLowerCase();
    result = result.filter(
      (item) =>
        item.name.toLowerCase().includes(search) ||
        item.description.toLowerCase().includes(search),
    );
  }

  return result;
});

const selectedItemsData = computed(() => {
  return surgeryItems.value.filter((item) =>
    selectedItems.value.includes(item.id),
  );
});

const totalAmount = computed(() => {
  return selectedItemsData.value.reduce((total, item) => total + item.price, 0);
});

// 方法
const onCategoryChange = () => {
  selectedItems.value = [];
};

const searchSurgery = () => {
  // 搜索逻辑已在计算属性中实现
};

const toggleItem = (itemId: string) => {
  const index = selectedItems.value.indexOf(itemId);
  if (index === -1) {
    selectedItems.value.push(itemId);
  } else {
    selectedItems.value.splice(index, 1);
  }
};

const removeItem = (itemId: string) => {
  const index = selectedItems.value.indexOf(itemId);
  if (index !== -1) {
    selectedItems.value.splice(index, 1);
  }
};

const handleOk = () => {
  if (selectedItems.value.length === 0) {
    message.warning('请至少选择一个手术项目');
    return;
  }

  if (!surgeryDate.value) {
    message.warning('请选择手术日期');
    return;
  }

  if (!surgeon.value) {
    message.warning('请选择主刀医生');
    return;
  }

  // 获取选中的项目数据
  const selectedItemsData = surgeryItems.value.filter((item) =>
    selectedItems.value.includes(item.id),
  );

  message.success('手术项目添加成功');
  emit('success', selectedItemsData);
  emit('update:visible', false);

  // 重置选择
  resetForm();
};

const handleCancel = () => {
  emit('update:visible', false);
  resetForm();
};

const resetForm = () => {
  selectedItems.value = [];
  searchQuery.value = '';
  surgeryDate.value = null;
  surgeryTime.value = null;
  surgeon.value = '';
  anesthesiologist.value = '';
  surgeryNotes.value = '';
};

// 监听模态框关闭
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      resetForm();
    }
  },
);
</script>

<template>
  <a-modal
    :open="visible"
    title="添加手术项目"
    width="800px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="surgery-modal">
      <!-- 手术分类选择 -->
      <div class="category-section">
        <h4>手术分类</h4>
        <a-radio-group
          v-model:value="selectedCategory"
          @change="onCategoryChange"
        >
          <a-radio-button value="emergency">急诊手术</a-radio-button>
          <a-radio-button value="elective">择期手术</a-radio-button>
          <a-radio-button value="minor">小手术</a-radio-button>
          <a-radio-button value="major">大手术</a-radio-button>
        </a-radio-group>
      </div>

      <!-- 手术项目列表 -->
      <div class="items-section">
        <h4>手术项目</h4>
        <div class="search-row">
          <a-input
            v-model:value="searchQuery"
            placeholder="搜索手术项目"
            style="width: 300px"
            @keyup.enter="searchSurgery"
          >
            <template #suffix>
              <a-button type="text" @click="searchSurgery">🔍</a-button>
            </template>
          </a-input>
        </div>
        <div class="items-grid">
          <div
            v-for="item in filteredItems"
            :key="item.id"
            class="item-card"
            :class="{ selected: selectedItems.includes(item.id) }"
            @click="toggleItem(item.id)"
          >
            <div class="item-name">{{ item.name }}</div>
            <div class="item-desc">{{ item.description }}</div>
            <div class="item-price">¥{{ item.price.toFixed(2) }}</div>
            <div class="item-duration">预计时长: {{ item.duration }}</div>
          </div>
        </div>
      </div>

      <!-- 已选项目 -->
      <div class="selected-section" v-if="selectedItems.length > 0">
        <h4>已选手术项目</h4>
        <a-table
          :columns="selectedColumns"
          :data-source="selectedItemsData"
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'price'">
              ¥{{ record.price.toFixed(2) }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-button
                type="text"
                danger
                size="small"
                @click="removeItem(record.id)"
              >
                删除
              </a-button>
            </template>
          </template>
        </a-table>

        <div class="total-section">
          <span class="total-label">总计:</span>
          <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 手术安排 -->
      <div class="schedule-section">
        <h4>手术安排</h4>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="手术日期">
              <a-date-picker
                v-model:value="surgeryDate"
                format="YYYY-MM-DD"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="手术时间">
              <a-time-picker
                v-model:value="surgeryTime"
                format="HH:mm"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="主刀医生">
              <a-select
                v-model:value="surgeon"
                placeholder="选择主刀医生"
                style="width: 100%"
              >
                <a-select-option value="doctor1">张医生</a-select-option>
                <a-select-option value="doctor2">李医生</a-select-option>
                <a-select-option value="doctor3">王医生</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="麻醉医生">
              <a-select
                v-model:value="anesthesiologist"
                placeholder="选择麻醉医生"
                style="width: 100%"
              >
                <a-select-option value="anesth1">陈医生</a-select-option>
                <a-select-option value="anesth2">刘医生</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 注意事项 -->
      <div class="notes-section">
        <h4>注意事项</h4>
        <a-textarea
          v-model:value="surgeryNotes"
          placeholder="请输入手术注意事项..."
          :rows="3"
        />
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.surgery-modal {
  max-height: 700px;
  overflow-y: auto;
}

.category-section {
  margin-bottom: 24px;
}

.category-section h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.items-section {
  margin-bottom: 24px;
}

.items-section h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.search-row {
  margin-bottom: 16px;
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.item-card {
  padding: 12px;
  cursor: pointer;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  transition: all 0.3s;
}

.item-card:hover {
  border-color: #1890ff;
}

.item-card.selected {
  background: #e6f7ff;
  border-color: #1890ff;
}

.item-name {
  margin-bottom: 4px;
  font-weight: 600;
  color: #262626;
}

.item-desc {
  margin-bottom: 4px;
  font-size: 12px;
  line-height: 1.4;
  color: #666;
}

.item-price {
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 600;
  color: #f5222d;
}

.item-duration {
  font-size: 12px;
  color: #1890ff;
}

.selected-section {
  padding-top: 16px;
  margin-bottom: 24px;
  border-top: 1px solid #f0f0f0;
}

.selected-section h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.total-section {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: flex-end;
  padding-top: 12px;
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.total-label {
  font-size: 14px;
  color: #666;
}

.total-amount {
  font-size: 18px;
  font-weight: 700;
  color: #f5222d;
}

.schedule-section {
  margin-bottom: 24px;
}

.schedule-section h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.notes-section {
  margin-bottom: 16px;
}

.notes-section h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}
</style>
